<template>
  <div class="dashboard-container">
    <div>  <!--style="margin: 0px auto; width: 50%;"-->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
               label-position="left">
        <el-form-item label="师资名称：" prop="teacher_name">
          <el-input v-model="ruleForm.teacher_name" placeholder="请输入师资名称"></el-input>
        </el-form-item>
        <!--<el-form-item label="校区城市：" class="demo-ruleForm1">
          <el-select @change="queryTwoLevel(ruleForm.campus_provinceid)" v-model="ruleForm.campus_provinceid" filterable
                     placeholder="一级分类">
            <el-option v-for="item in oneLevel" :key="item.id" :label="item.city_name" :value="item.id">
            </el-option>
          </el-select>
          <el-select @change="queryThreeLevel(ruleForm.campus_cityid)" v-model="ruleForm.campus_cityid"
                     filterable placeholder="二级分类">
            <el-option v-for="item in twoLevel" :key="item.id" :label="item.city_name" :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="ruleForm.campus_areaid" filterable placeholder="三级分类">
            <el-option v-for="item in threeLevel" :key="item.id" :label="item.city_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>-->
        <!--   <el-form-item label="校区地址：" prop="campus_address">
             <el-input v-model="ruleForm.campus_address" placeholder="请输入校区地址"></el-input>
           </el-form-item>-->

        <el-form-item label-width="180" label="机构师资形象图：">
          <el-upload ref="upload" action="#"
                     :limit="1"
                     :http-request="submitUpload"
                     :file-list="dataForm.imgFileList"
                     list-type="picture-card"
                     :before-upload="beforeAvatarUpload"
                     :on-preview="handlePictureCardPreview"
                     :on-change="OnChange"
                     :on-remove="handleRemove"
                     :on-exceed="handleExceed"
                     accept="image/jpeg,image/png">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">图片不允许超过500kb</div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-card class="box-card">
          <el-row>
            <el-col :span="24">
              <div class="grid-content bg-purple-dark">
                <el-form-item
                  label="开设课程："
                  prop="region"
                  class="demo-ruleForm1"
                >
                  <el-select
                    @change="queryTwoLevelClass(course_parentid)"
                    v-model="course_parentid"
                    filterable
                    placeholder="一级分类"
                  >
                    <el-option
                      v-for="item in oneClass"
                      :key="item.id"
                      :label="item.cat_name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    @change="queryThreeLevelClass(course_secondid)"
                    v-model="course_secondid"
                    filterable
                    placeholder="二级分类"
                  >
                    <el-option
                      v-for="item in twoClass"
                      :key="item.id"
                      :label="item.cat_name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    @change="queryLastLevelClass(course_catid)"
                    v-model="course_catid"
                    filterable
                    placeholder="三级分类"
                  >
                    <el-option
                      v-for="item in threeClass"
                      :key="item.id"
                      :label="item.cat_name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-col :span="12">
            <el-form-item label="课程搜索：">
              <el-input
                clearable
                v-model="course_title"
                placeholder="请输入课程名称进行搜索"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button @click="changeSearch" type="primary">搜索</el-button>
          </el-col>
          <el-col :span="4">
            <el-button @click="reset" type="primary">重置</el-button>
          </el-col>

          <el-table
            ref="dataTable"
            @select="selectOne"
            :row-key="getRowKey"
            @selection-change="handleSelectionChange"
            :data="list"
            height="800"
            style="width: 100%"
            :header-cell-style="{ background: '#f1f1f1', color: '#333' }"
          >
            <el-table-column
              :reserve-selection="true"
              type="selection"
              width="55"
            >
            </el-table-column>
            <el-table-column label="id" align="center">
              <template slot-scope="scope">{{ scope.row.id }}</template>
            </el-table-column>
            <el-table-column label="课程标题" align="center">
              <template slot-scope="scope">{{
                  scope.row.course_title
                }}</template>
            </el-table-column>
            <el-table-column label="所属分类" align="center">
              <template slot-scope="scope">{{ scope.row.cat_name }}</template>
            </el-table-column>
            <el-table-column prop="img" align="center" label="缩略图">
              <template slot-scope="scope">
                <img
                  :src="scope.row.images"
                  alt=""
                  style="height: 60px; max-width: 100%;"
                />
              </template>
            </el-table-column>
            <!--      <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row),$router.push('/nested/menu4/menu1-8')">
                      编辑
                    </el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                  </template>
                </el-table-column>-->
          </el-table>
        </el-card>


        <el-form-item label="是否发布：" prop="campus_status">
          <el-radio-group v-model="ruleForm.campus_status">
            <el-radio :label="0">未发布</el-radio>
            <el-radio :label="1">已发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序：" prop="teacher_orderid">
          <el-input v-enter-number v-model="ruleForm.teacher_orderid" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item label="机构师资简介：" prop="teacher_content" class="form-item-xqjs">
          <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 6}" placeholder="请输入机构师资简介"
                    v-model="ruleForm.teacher_content"></el-input>
        </el-form-item>
        <div class="el-select"
             style="width: 100%;margin-top: 15px;display: flex;align-items: center;justify-content: center;">
          <el-button type="primary" class="div-button" @click="submitForm('ruleForm')">确定</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  cateComList, cityComList, uploadImg, courseComList, cateList, campusAdd, schoolAdd,
  teacherAdd, schoolCourseIds
} from "@/api/menu";
import {mapGetters} from "vuex";

export default {
  data() {
    return {
      course_title: "",
      hasCheckId: [],
      hasSelectList: [], //已经选择的id组成的数组
      course_parentid: '',
      course_secondid: '',
      course_catid: '',
      list: [],
      listQuery: {
        page: 1,
        page_size: 10
      },
      total: null,
      currentPage: 1,
      oneClass: [],
      twoClass: [],
      threeClass: [],
      dataForm: {
        imgFileList: []//绑定用户上传的图片List
      },
      dialogVisible: false,
      dialogImageUrl: '',
      oneLevel: [],
      twoLevel: [],
      threeLevel: [],
      ruleForm: {
        teacher_name: '',
        teacher_images: '',
        teacher_content: '',
        teacher_orderid: '',
        teacher_courseid: [],
      },
      rules: {
        teacher_name: [{
          required: true,
          message: '请输入老师名称',
          trigger: 'blur'
        }],
        campus_address: [{
          required: true,
          message: '请输入校区地址',
          trigger: 'blur'
        }],
        teacher_content: [{
          required: true,
          message: '请填写机构师资简介',
          trigger: 'blur'
        }],
        teacher_orderid: [{
          required: true,
          message: '请输入排序',
          trigger: 'blur'
        }]
      },
      fileList: [{
        name: 'logo.jpeg',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      }],
      textarea2: '',
      input: '',
      allIds: [],
      needIds: [],
      isIndeterminate: false, //对el-checkbox控制不完整的全选状态
      checkAll: false, //对el-checkbox控制全选状态
      checkList: [],
      myNeedIds: [],
      flag:false
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'schoolId'
    ]),
  },
  mounted() {
    this.getOneLevel()
    this.getOneLevelClass()
    this.getCourseComList()
    this.getSchoolCourseIds();
  },
  watch: {
    list: {
      handler(value) {
        if (this.allCheck) {
          let that = this;
          let len = that.checkList.length;
          value.forEach(row => {
            for (let i = 0; i < len; i++) {
              if (row.id === that.checkList[i].id) {
                that.$refs.dataTable.toggleRowSelection(row, false);
                break;
              } else {
                that.$refs.dataTable.toggleRowSelection(row, true);
              }
            }
          });
        }
        const that = this;
        that.$nextTick(() => {
          for (let i = 0; i < that.list.length; i++) {
            that.$refs.dataTable.toggleRowSelection(that.list[i], true);
          }
        });
      },
      deep: true
    }
  },
  methods: {
    getRowKey(row) {
      return row.id;
    },
    /**
     * 获取所有课程的id
     */
    setSchoolCourseIds(ids) {
      schoolCourseIds({
        course_schoolid: this.schoolId,
        course_parentid: this.course_parentid,
        course_secondid: this.course_secondid,
        course_catid: this.course_catid,
        courseids: ids
      })
        .then(response => {
          console.log(response);
          this.needIds = response.data.ids;
        })
        .catch(e => {});
    },
    getSchoolCourseIds() {
      schoolCourseIds({
        course_schoolid: this.schoolId,
        course_parentid: "",
        course_secondid: "",
        course_catid: ""
      })
        .then(response => {
          console.log(response);
          this.allIds = response.data.ids;
        })
        .catch(e => {});
    },
    selectOne(selection, row) {
      this.flag=true
      if (this.needIds.indexOf(row.id) != -1) {
        let found = this.needIds.find(element => element == row.id);
        let isLargeNumber = element => element == row.id;
        let index = this.needIds.findIndex(isLargeNumber);
        this.needIds = this.needIds.splice(0, index);
      } else {
        this.needIds.push(row.id);
      }
      schoolCourseIds({
        course_schoolid:this.schoolId,
        course_parentid: this.course_parentid,
        course_secondid: this.course_secondid,
        course_catid: this.course_catid,
        courseids: this.needIds.length == 0 ? 0 : this.needIds
      })
        .then(response => {
          console.log(response);
          this.myNeedIds = response.data.ids;
          console.log(this.myNeedIds);
          let aaa = response.data.ids;
          for (let i = 0; i < this.list.length; i++) {
            if (aaa.indexOf(this.list[i].id) != -1) {
              this.$refs.dataTable.toggleRowSelection(this.list[i], false);
            }
          }
        })
        .catch(e => {});
    },
    /**
     * 表格复选框全选
     */
    checked() {
      const that = this;
      that.$nextTick(() => {
        for (let i = 0; i < that.list.length; i++) {
          that.$refs.dataTable.toggleRowSelection(that.list[i], true);
        }
      });
    },
    /**
     * 获取表格选中内容
     */
    handleSelectionChange(val) {
      this.checkList = val;
    },
    changeSearch() {
      this.getCourseComList();
    },
    reset() {
      this.course_title = "";
      this.course_parentid = "";
      this.course_parentid = "";
      this.course_secondid = "";
      this.course_catid = "";
      this.getCourseComList();
    },
    /**
     * 获取分类课程数据
     */
    getCourseComList() {
      this.listLoading = true;
      courseComList({
        course_title: this.course_title,
        course_schoolid: this.schoolId,
        course_parentid: this.course_parentid,
        course_secondid: this.course_secondid,
        course_catid: this.course_catid,
        page: this.listQuery.page,
        page_size: this.listQuery.page_size
      }).then(response => {
        this.listLoading = false;
        console.log(response);
        this.list = response.data.data_list
        this.total = response.data.total
      }).catch((e) => {
      });
    },
    handleSizeChange(val) {
      this.listQuery.page_size = val
      this.getCourseComList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getCourseComList()
    },
    /**
     * 查询二级数据
     */
    queryTwoLevelClass(value) {
      console.log(value);
      this.course_secondid = '';
      this.course_catid = '';
      cateComList({
        cate_parentid: value,
        cate_secondid: 0
      }).then(response => {
        console.log(response);
        this.twoClass = response.data
        this.twoClass.unshift({id: "", cat_name: "请选择"})
      })
    },
    /**
     * 查询三级数据
     */
    queryThreeLevelClass(value) {
      this.course_catid = '';
      console.log(value);
      cateComList({
        cate_parentid: value,
        cate_secondid: this.course_parentid
      }).then(response => {
        console.log(response);
        this.threeClass = response.data
        this.threeClass.unshift({id: "", cat_name: "请选择"})
      })
    },
    /**
     * 获取一级数据
     */
    getOneLevelClass() {
      cateComList({
        cate_parentid: 0,
        cate_secondid: 0
      }).then(response => {
        console.log(response);
        this.oneClass = response.data
        this.oneClass.unshift({id: "", cat_name: "请选择"})
      })
    },
    /**
     * 图片上传前校验
     * @param file
     */
    beforeAvatarUpload(file) {
      var testmsg = /^image\/(jpeg|png|jpg)$/.test(file.type)
      const isLt1M = file.size / 1024 / 1024 /0.5< 1//图片大小不超过2MB
      if ( !testmsg ) {
        this.$message.error('上传图片格式不对!');
        return
      }
      if ( !isLt1M ) {
        this.$message.error('上传图片大小不能超过 500kb!');
        return
      }
      return testmsg && isLt1M
    },
    /**
     * 文件超出个数限制时
     * @param files
     * @param fileList
     */
    handleExceed(files, fileList) {
      this.$message.warning(`只允许上传一张图片`);
    },
    /**
     * 点击上传图片
     */
    submitUpload() {
      let formData = new FormData(); //  用FormData存放上传文件
      this.dataForm.imgFileList.forEach(file => {
        console.log(file);
        formData.append('file', file.raw)
      })
      uploadImg(formData).then(response => {
        console.log(response);
        this.ruleForm.teacher_images = response.data
      })
    },
    /**
     * 预览图片时
     * @param file
     */
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /**
     * 文件上传状态改变
     * @param file
     * @param fileList
     * @constructor
     */
    OnChange(file, fileList) {
      const isType = file.type === 'image/jpeg' || 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 1

      if ( !isType ) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
        fileList.pop()
      }
      if ( !isLt5M ) {
        this.$message.error('上传头像图片大小不能超过 1MB!');
        fileList.pop()
      }
      this.dataForm.imgFileList.push(file)
      this.hideUpload = fileList.length >= this.limit

    },
    /**
     * 删除图片时
     * @param file
     * @param fileList
     */
    handleRemove(file, fileList) {
      if ( file.id ) {
        console.log('删除了已被上传过的图片')
        console.log(file.id)
        this.deleteImgFileList.push(file.id)
      }
      this.dataForm.imgFileList = fileList
      this.hideUpload = fileList.length >= this.limit
    },
    /**
     * 市
     */
    queryTwoLevel(value) {
      console.log(value);
      this.ruleForm.campus_cityid = '';
      this.ruleForm.campus_areaid = '';
      cityComList({
        city_provinceid: value,
        city_cityid: 0
      }).then(response => {
        console.log(response);
        this.twoLevel = response.data
      })
    },
    /**
     * 区
     */
    queryThreeLevel(value) {
      this.ruleForm.campus_areaid = '';
      console.log(value);
      cityComList({
        city_provinceid: value,
        city_cityid: this.ruleForm.campus_provinceid
      }).then(response => {
        console.log(response);
        this.threeLevel = response.data
      })
    },
    /**
     * 省
     */
    getOneLevel() {
      cityComList({
        city_provinceid: 0,
        city_cityid: 0
      }).then(response => {
        console.log(response);
        this.oneLevel = response.data
      })
    },
    handlePreview(file) {
      console.log(file);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    submitForm(formName) {
      this.$refs[ formName ].validate((valid) => {
        if ( valid ) {
          teacherAdd(Object.assign(this.ruleForm, {teacher_schoolid: this.schoolId, teacher_courseid:this.flag?this.myNeedIds:this.allIds})).then(response => {
            this.listLoading = false;
            console.log(response);
            this.$message({message: '提交成功', type: 'success', duration: 1000});
            this.$router.push({path: '/teacherList', query: {id: this.$route.query.id}});
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[ formName ].resetFields();
    }
  }
}
</script>

<style scoped>
.block-div {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 20px;
}

.el-upload__tip {
  margin: 0 20px;
  height: 46px;
  overflow: hidden;
  display: inline-block;
}

.form-item-xqjs /deep/ .el-form-item__label {
  width: 100px;
  height: 138px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.demo-ruleForm1 /deep/ .el-form-item__content {
  display: flex;
}

.demo-ruleForm1 /deep/ .el-select {
  width: 100%;
}

.xzfl-div /deep/ .el-select {
  width: 100%;
}

.tp-div {
  width: 100%;
  margin: 0 auto;
  text-align: center;
  height: auto;
}

.cstp-div /deep/ .el-upload-list__item:first-child {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  margin-top: 0;
  margin-left: 10px;
}

.cstp-div /deep/ .el-upload-list__item.is-success .el-upload-list__item-status-label {
  height: 100%;
  display: flex;
  align-items: center;
}

.cstp-div /deep/ .el-upload-list__item .el-icon-close {
  top: 13px;
  background: #f5f7fa;
}

.cstp-div /deep/ .el-upload-list__item .el-icon-close-tip {
  display: none !important;
}

.tp-div /deep/ .el-upload {
  display: none !important;
}

.tp-div /deep/ .el-upload-list--picture .el-upload-list__item {
  width: 49%;
  display: inline-block;
  padding: 10px 10px 10px 140px;
}

.tp-div /deep/ .el-upload-list--picture .el-upload-list__item:nth-child(2),
.tp-div /deep/ .el-upload-list--picture .el-upload-list__item:nth-child(4),
.tp-div /deep/ .el-upload-list--picture .el-upload-list__item:nth-child(6).tp-div /deep/ .el-upload-list--picture .el-upload-list__item:nth-child(8).tp-div /deep/ .el-upload-list--picture .el-upload-list__item:nth-child(10) {
  margin-left: 2%;
}

.tp-div /deep/ .el-upload-list--picture .el-upload-list__item-thumbnail {
  width: 123px;
  height: auto;
  margin-left: -130px;
}

.tp-div /deep/ .el-upload-list__item-name {
  margin-right: 0;
  width: 85%;
}
</style>

<style lang="scss" scoped>
.left {
  float: left;
}

.tp-div1 {
  display: inline-block;
  border: 1px solid #dcdfe6;
  padding: 15px;
  width: 80%;
  text-align: center;
}

.tp-div1:nth-child(2),
.tp-div1:nth-child(4),
.tp-div1:nth-child(6),
.tp-div1:nth-child(8),
.tp-div1:nth-child(10),
.tp-div1:nth-child(12) {
  margin-left: 16px;
}

.tp-div1:nth-child(1),
.tp-div1:nth-child(2) {
  margin-top: 10px;
}

.tp-div1-img {
  font-size: 0;
  width: 40%;
  /*  height: 80px;*/
}

.tp-div1-img > img {
  width: 100%;
}

.tp-div1-text {
  margin: 0 15px;
  height: 80px;
  line-height: 20px;
  overflow: hidden;
  width: 41%;
  display: flex;
  flex-flow: row wrap;
  align-items: center;
}

.tp-div1-text > p:nth-child(2) {
  color: #a3a6ad;
}

.div-button {
  width: 15%;
}

.el-icon-delete {
  margin: 20px 0;
  font-size: 36px;
  color: #a3a6ad;
  cursor: pointer;
}

.dashboard-container p {
  margin: 0;
}

.dashboard {
  &-container {
    margin: 0 15px;
    padding: 30px;
    background-color: #fff;
  }

  &-text {
    font-size: 16px;
  }
}
</style>
